package com.adou.json;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import jdk.management.resource.internal.inst.SimpleAsynchronousFileChannelImplRMHooks;

import org.junit.Test;

import com.adou.domain.Product;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.PropertyFilter;
import com.alibaba.fastjson.serializer.SerializeFilter;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.serializer.SimplePropertyPreFilter;
import com.sun.xml.internal.fastinfoset.sax.Properties;

public class JsonTest {

	// 将一个project转换json
	@Test
	public void test1(){
		Product p1 = new Product();
		p1.setId(1);
		p1.setName("西瓜");
		p1.setCount(5);
		p1.setPrice(20.0);
		p1.setpDate(new Date());
		
		SerializeFilter filter = new PropertyFilter() {
			// 对数据进行过滤
			@Override
			public boolean apply(Object arg0, String arg1, Object arg2) {
				//arg0 类名
				//arg1属性名
				//arg2属性值
				if("biaohao".equals(arg1)){
					return false;
				}
				return true;
			}
		};
		
		// 需要属性加进来
		SerializeFilter filter2 = new SimplePropertyPreFilter("biaohao", "name");
		
		
		String json = JSONObject.toJSONString(p1, filter);
		System.out.println(json);
		
	}
	
	//将List<Person> 转换json
	@Test
	public void test2(){
		List<Product> ps = new ArrayList<Product>();
		
		Product p1 = new Product();
		p1.setId(1);
		p1.setName("西瓜");
		p1.setCount(5);
		p1.setPrice(20.0);
		
		Product p2 = new Product();
		p2.setId(2);
		p2.setName("苹果");
		p2.setCount(6);
		p2.setPrice(16.0);
		
		ps.add(p1);
		ps.add(p2);
		
		//[{},{}]
		String json = JSONObject.toJSONString(ps);
		System.out.println(json);
	}

	
	/**
	 * 重复数据，循环引用
	 * [{"biaohao":1,"count":5,"name":"西瓜","price":20},{"$ref":"$[0]"},{"$ref":"$[0]"}]
	 */
	@Test
	public void test3(){
		Product p1 = new Product();
		p1.setId(1);
		p1.setName("西瓜");
		p1.setCount(5);
		p1.setPrice(20.0);
		
		List<Product> ps = new ArrayList<Product>();
		ps.add(p1);
		ps.add(p1);
		ps.add(p1);
		
		String json = JSONObject.toJSONString(ps, SerializerFeature.DisableCircularReferenceDetect);
		System.out.println(json);
	}
}
